package com.valdemar.cookerybook.dao;

import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Hashtable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.valdemar.cookerybook.model.Course;
import com.valdemar.cookerybook.model.Ingredient;

public enum CourseDao 
{
	instance;
	
	
	
	public List<Course> listAll(int languageId)
	{
		List<Course> list = BaseEntityHelperDao.listAll(languageId, Course.class);
		
		return list;
	}
	
	public void add(String code, int langID, String translation)
	{
		synchronized (this)
		{
			EntityManager em = EMFService.get().createEntityManager();
			
			Course course = new Course(code);
			em.persist(course);
			em.close();

			TranslationDao.instance.add(Course.class.getName(), course, langID);
		}
	}
	
	public Course get(long id)
	{
		EntityManager em = EMFService.get().createEntityManager();
		Course course = null;
		try
		{
			course = em.find(Course.class, id);
		}
		finally
		{
			em.close();
		}
		return course;
	}

	public Course get(String code, int languageId)
	{
		EntityManager em = EMFService.get().createEntityManager();
		Course course = null;
		try
		{

			Query q = em.createQuery("select i from Course i where i.code = :code");
			q.setParameter("code", code);
			course = (Course) q.getSingleResult();

			if (course == null)
				return null;
			String tr = TranslationDao.instance.getTranslation(Course.class.getName(), code, languageId);

			course.setTranslate(tr);
		}
		finally
		{
			em.close();
		}
		return course;
	}


	public int getCount()
	{
		EntityManager em = EMFService.get().createEntityManager();
		
		Query q = em.createQuery("select count(m) from Course m");
		
		Integer count = (Integer) q.getSingleResult();
		
		return count;
	}


	public void addBulk(String courses, int languageId)
	{
		Gson gson = new Gson();
		
		Type collectionType = new TypeToken<Collection<Course>>(){}.getType();
		Collection<Course> ints2 = gson.fromJson(courses, collectionType);
		
		
	}
	
	
	
}
